package gui;

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import utils.node.DisplayNode;
import utils.ServerConnection;
import utils.node.RootNode;

/**
 *
 */
public class ServersPanel extends JPanel
{
    private final ChatsPanel chatsPanel_;
    private final RootNode top_ = new RootNode( "Servers" );
    private final JTree servers_ = new JTree( top_ );
    
    public ServersPanel( ChatsPanel chatsPanel )
    {
        chatsPanel_ = chatsPanel;
        top_.setTree((DefaultTreeModel)servers_.getModel());
        
        setLayout( new BorderLayout() );
        add( servers_, BorderLayout.CENTER );
        servers_.setExpandsSelectedPaths(true);
        servers_.setRootVisible( true );
        servers_.setShowsRootHandles( true );
        servers_.setScrollsOnExpand( true );
        
        servers_.getSelectionModel()
                .setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
        servers_.addTreeSelectionListener( new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node
                        = (DefaultMutableTreeNode) servers_.getLastSelectedPathComponent();
                if( node == null || node.isRoot() )
                    return;
                chatsPanel_.setCurrentDisplay( ((DisplayNode) node).getDisplay() );
            }
        });
        servers_.addMouseListener( new MouseListener() {
            public void mouseClicked(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {
                if( e.getButton() != 2 )
                    return;
                
                TreePath path = ((JTree)e.getSource())
                        .getClosestPathForLocation( e.getX(), e.getY() );
                
                if( path == null )
                    return;
                
                DefaultMutableTreeNode node =
                        (DefaultMutableTreeNode) path.getLastPathComponent();
                if( !node.isRoot() )
                    ((DisplayNode) node).remove();
            }
        });
    }
    
    public void add( ServerConnection server )
    {
        ((DefaultTreeModel) servers_.getModel())
                .insertNodeInto(server.getNode(), top_, top_.getChildCount() );
    }
}
